package com.dzl.userwx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dzl.base.controller.BaseController;
import com.dzl.userwx.pojo.WelfareUserWx;
import com.dzl.userwx.pojo.query.WelfareUserWxIdQuery;
import com.dzl.userwx.pojo.vo.LoginWxUserInfoVo;
import com.dzl.userwx.pojo.vo.UserWxIntegraDetaillVo;
import com.dzl.userwx.pojo.vo.WelfareUserCommonVo;
import com.dzl.userwx.service.WelfareUserWxService;
import com.dzl.util.*;
import com.dzl.util.wx.constant.WxConstant;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 小程序用户表相关操作
 * @author liuguanjun
 * @since 2021-09-07 11:26:26
 **/
@Slf4j
@RestController
@RequestMapping("welfareUserWx")
public class WelfareUserWxController extends BaseController {

    @Autowired
    private WelfareUserWxService service;

    /**
     * 获取openid
     * @date 2021/09/07 13:45
     * @author liuguanjun
     * @param request 临时授权码
     */
    @GetMapping(value="/getOpenid")
    public JsonResult<String> getOpenId(HttpServletRequest request) throws IOException {
        String code = request.getParameter("code");
        //appid
        String appid = WxConstant.SAAS_APPID;
        String secret = WxConstant.SAAS_APPSCERET;
        if(EmptyUtils.isEmpty(code)) {
            return JsonResult.paramErrWithMsg("缺少参数[code:临时授权码]");
        }
        HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code");
        //设置请求器的配置
        HttpClient httpClient = HttpClients.createDefault();
        HttpResponse res = httpClient.execute(httpGet);
        HttpEntity entity = res.getEntity();
        String result = EntityUtils.toString(entity, "UTF-8");
        System.out.println("根据code："+code+"，获取的openid为："+result);
        if(EmptyUtils.isNotEmpty(result)){
            JSONObject object = JSONObject.parseObject(result);
            if(object!=null && EmptyUtils.isNotEmpty(object.getString("openid"))){
                return JsonResult.success(object.getString("openid"));
            }
        }
        return JsonResult.failWithMsg("获取openid失败");
    }

    /**
     * 根据openid获取用户信息是否绑定某企业（进入过企业主页）
     * @date 2021/09/07 14:14
     * @author liuguanjun
     * @param openid 微信openid
     */
    @GetMapping(value="/getEnterpriseId")
    public JsonResult<Integer> getEnterpriseId(String openid)  {
        if(EmptyUtils.isEmpty(openid)) {
            return JsonResult.paramErrWithMsg("缺少参数[openid]");
        }
        Integer enterpriseId = service.getWxUserInfoEnterpriseId(openid);
        if(EmptyUtils.isNotEmpty(enterpriseId)){
            return JsonResult.success(enterpriseId);
        }else{
            return JsonResult.failWithMsg("未绑定过企业");
        }
    }

    /**
     * Saas小程序登录验证
     * @date 2021/09/07 09:40
     * @author liuguanjun
     * @param param 企业id等参数
     */
    @PostMapping(value="/login")
    public JsonResult<String> login(@RequestBody JSONObject param) {
        Integer enterpriseId=param.getIntValue("enterpriseId");//企业id
        String openid=param.getString("openid");//微信openid
        String phone=param.getString("phone");//用户名
        String password=param.getString("password");//密码
        if(EmptyUtils.isEmpty(openid)) {
            return JsonResult.paramErrWithMsg("缺少参数[openid]");
        }
        if(EmptyUtils.isEmpty(phone)||EmptyUtils.isEmpty(password)) {
            return JsonResult.paramErrWithMsg("请输入用户名或密码");
        }
        //登录
        String token=service.login(enterpriseId,openid, phone, password);
        return JsonResult.success(token);
    }

    /**
     * 获取登录用户详细信息
     * @date 2021/09/07 11:52
     * @author liuguanjun
     */
    @GetMapping("getUserInfo")
    public JsonResult<LoginWxUserInfoVo> getLoginUserInfo() {
        LoginWxUserInfoVo loginWxUserInfoVo = new LoginWxUserInfoVo();
        WelfareUserWx welfareUserWx = service.selectByPrimaryKey(getWxUserInfo().getId());
        BeanUtils.copyProperties(welfareUserWx,loginWxUserInfoVo);
        return JsonResult.success(loginWxUserInfoVo);
    }

    /**
     * 忘记密码，修改支付密码
     * @date 2021/9/08 15:40
     * @author liuguanjun
     * @param param 原登录密码,新登录密码等参数
     */
    @PostMapping("/forgetPassword")
    public JsonResult<String> forgetPassword(@RequestBody JSONObject param) {
        //LoginWxUserInfoVo userInfoVo = getWxUserInfo();
        Integer enterpriseId=param.getIntValue("enterpriseId");
        String phone=param.getString("phone");
        String oldPwd = param.getString("oldPwd");//原登录密码
        String newPwd = param.getString("newPwd");//新登录密码
        if(EmptyUtils.isEmpty(phone)) {
            return JsonResult.paramErrWithMsg("请输入登录账号！");
        }
        if(EmptyUtils.isEmpty(oldPwd) || EmptyUtils.isEmpty(newPwd)) {
            return JsonResult.paramErrWithMsg("请输入原密码和新密码！");
        }
        WelfareUserWx query = new WelfareUserWx();
        query.setEnterpriseId(enterpriseId);
        query.setPhone(phone);
        List<WelfareUserWx> welfareUserWxList = service.select(query);
        if(EmptyUtils.isEmpty(welfareUserWxList)){
            return JsonResult.failWithMsg("该账号未注册");
        }
        WelfareUserWx userWx = welfareUserWxList.get(0);
        //检验原登录密码是否正确
        if(!oldPwd.equals(PasswordUtil.AESDecrypt(userWx.getPassword()))) {
            return JsonResult.paramErrWithMsg("原密码输入有误！");
        }
        //执行修改密码
        userWx.setUpdateTime(new Date());
        userWx.setPassword(PasswordUtil.AESEncrypt(newPwd));
        service.updateByPrimaryKeySelective(userWx);
        return JsonResult.success("修改密码成功");
    }

    /**
     * 修改登录密码
     * @date 2021/9/07 11:55
     * @author liuguanjun
     * @param param 原登录密码,新登录密码等参数
     */
    @PostMapping("/updatePassword")
    public JsonResult<String> updatePassword(HttpServletRequest request, @RequestBody JSONObject param) {
        LoginWxUserInfoVo userInfoVo = getWxUserInfo();
        String oldPwd = param.getString("oldPwd");//原登录密码
        String newPwd = param.getString("newPwd");//新登录密码
        if(EmptyUtils.isEmpty(oldPwd) || EmptyUtils.isEmpty(newPwd)) {
            return JsonResult.paramErrWithMsg("请输入原密码和新密码！");
        }
        //检验原登录密码是否正确
        if(!oldPwd.equals(PasswordUtil.AESDecrypt(userInfoVo.getPassword()))) {
            return JsonResult.paramErrWithMsg("原密码输入有误！");
        }
        //执行修改密码
        WelfareUserWx userWx = new WelfareUserWx();
        userWx.setId(userInfoVo.getId());
        userWx.setPassword(PasswordUtil.AESEncrypt(newPwd));
        userWx.setUpdateTime(new Date());
        service.updateByPrimaryKeySelective(userWx);
        //更新token到redis
        userInfoVo.setPassword(PasswordUtil.AESEncrypt(newPwd));
        String token= request.getHeader("token");
        RedisUtil.set(token, JSON.toJSONString(userInfoVo) ,60*60*24*3);//缓存3天
        return JsonResult.success("修改登录密码成功");
    }


    /**
     * 修改支付密码
     * @date 2021/9/08 15:56
     * @author liuguanjun
     * @param param 原登录密码,新登录密码等参数
     */
    @PostMapping("/updatePayPassword")
    public JsonResult<String> updatePayPassword(HttpServletRequest request, @RequestBody JSONObject param) {
        LoginWxUserInfoVo userInfoVo = getWxUserInfo();
        String oldPwd = param.getString("oldPwd");//原登录密码
        String newPwd = param.getString("newPwd");//新支付密码
        if(EmptyUtils.isEmpty(oldPwd) || EmptyUtils.isEmpty(newPwd)) {
            return JsonResult.paramErrWithMsg("请输入原密码和新密码！");
        }
        //校验初始密码是否为空
        if(EmptyUtils.isEmpty(userInfoVo.getPayPassword())) {
            return JsonResult.paramErrWithMsg("初始密码为空，导入员工数据时出错！");
        }
        //检验原登录密码是否正确
        if(!oldPwd.equals(PasswordUtil.AESDecrypt(userInfoVo.getPayPassword()))) {
            return JsonResult.paramErrWithMsg("原密码输入有误！");
        }
        //执行修改密码
        WelfareUserWx userWx = new WelfareUserWx();
        userWx.setId(userInfoVo.getId());
        userWx.setPayPassword(PasswordUtil.AESEncrypt(newPwd));
        userWx.setUpdateTime(new Date());
        service.updateByPrimaryKeySelective(userWx);
        //更新token到redis
        userInfoVo.setPayPassword(PasswordUtil.AESEncrypt(newPwd));
        String token= request.getHeader("token");
        RedisUtil.set(token, JSON.toJSONString(userInfoVo) ,60*60*24*3);//缓存3天
        return JsonResult.success("修改支付密码成功");
    }

    /**
     * 修改电话号码
     * @date 2021/9/08 15:58
     * @author liuguanjun
     * @param param 原手机号,新手机号等参数
     */
    @PostMapping("/updatePhoneNumber")
    public JsonResult<String> updatePhone(HttpServletRequest request, @RequestBody JSONObject param) {
        LoginWxUserInfoVo userInfoVo = getWxUserInfo();
        String oldPhone = param.getString("oldPhoneNumber");//原手机号
        String newPhone = param.getString("newPhoneNumber");//新手机号
        // 电话号码不能为空（此处不对老电话号码做校验）
        if (EmptyUtils.isEmpty(newPhone)) {
            return JsonResult.paramErrWithMsgAndCode(1028,"请输入新手机号");
        }
        if (EmptyUtils.isEmpty(oldPhone)) {
            return JsonResult.paramErrWithMsgAndCode(1026, "请输入原手机号");
        }
        if (oldPhone.equals(newPhone)){
            return JsonResult.paramErrWithMsgAndCode(1027, "相同的手机号");
        }
        //检验原登录密码是否正确
        if(!oldPhone.equals(userInfoVo.getPhone())) {
            return JsonResult.paramErrWithMsgAndCode(1026,"原手机号输入有误");
        }
        //验证新手机号是否已存在
        Example welfareUserWxExample = new Example(WelfareUserWx.class);
        welfareUserWxExample.createCriteria().andEqualTo("enterpriseId", userInfoVo.getEnterpriseId()).andEqualTo("phone", newPhone).andNotEqualTo("id",userInfoVo.getId());
        int count = service.selectCountByExample(welfareUserWxExample);
        if(count > 0) {
            return JsonResult.paramErrWithMsgAndCode(1028,"新手机号已被绑定");
        }
        //执行修改密码
        WelfareUserWx userWx = new WelfareUserWx();
        userWx.setId(userInfoVo.getId());
        userWx.setPhone(newPhone);
        userWx.setUpdateTime(new Date());
        service.updateByPrimaryKeySelective(userWx);
        //更新token到redis
        userInfoVo.setPhone(newPhone);
        String token= request.getHeader("token");
        RedisUtil.set(token, JSON.toJSONString(userInfoVo) ,60*60*24*3);//缓存3天
        return JsonResult.success("修改手机号成功");
    }

    /**
     * 校验支付密码
     * @param ppwd 支付密码
     * @return com.dzl.util.JsonResult<java.lang.Object>
     * @author caobucao
     * @date 2021-05-27 12:38:32
     **/
    @PostMapping("validatePayPassword")
    public JsonResult<Integer> validatePayPassword(String ppwd) {
        log.info("validatePayPassword in");
        Integer userId = getWxUserInfo().getId();
        if (EmptyUtils.isEmpty(ppwd)) {
            return JsonResult.paramErrWithMsg("支付密码不能为空");
        }
        Example welfareUserWxExample = new Example(WelfareUserWx.class);
        welfareUserWxExample.createCriteria().andEqualTo("id", userId);
        WelfareUserWx welfareUserWx = service.selectOneByExample(welfareUserWxExample);
        if (EmptyUtils.isEmpty(welfareUserWx)) {
            return JsonResult.paramErrWithMsg("支付密码校验错误");
        }
        if (PasswordUtil.AESDecrypt(welfareUserWx.getPayPassword()).equals("1234")) {
            return JsonResult.paramErrWithMsg("请修改初始支付密码");
        }
        if (EmptyUtils.isEmpty(welfareUserWx.getPayPassword())) {
            return JsonResult.paramErrWithMsg("请设置支付密码");
        }
        String decPpwd = PasswordUtil.AESDecrypt(welfareUserWx.getPayPassword());
        if (!ppwd.equals(decPpwd)) {
            return JsonResult.paramErrWithMsg("支付密码错误");
        }
        return JsonResult.success();
    }

    /**
     * 获取用户综合信息（订单数量、卡密数量）
     * @return com.dzl.util.JsonResult<java.lang.Object>
     * @author ChenLong
     * @since 2021-05-17 17:32:38
     **/
    @GetMapping(value = "getWxUserCommonInfo")
    public JsonResult<WelfareUserCommonVo> getWxUserCommonInfo() {
        log.info("getWxUserCommonInfo in ");
        Integer userId = getWxUserInfo().getId();
        return JsonResult.success(service.getWxUserCommonInfo(userId));
    }

    /**
     * 获取积分明细
     * @author ChenLong
     * @date 2021-09-10 09:40:39
     * @return com.dzl.util.JsonResult
     **/
    @GetMapping(value="/getUserIntegralDetail")
    public PageUtils<UserWxIntegraDetaillVo> getUserIntegralDetail(WelfareUserWxIdQuery query){
        log.info("getUserIntegralDetail in");
        Integer userId = getWxUserInfo().getId();
        query.setUserId(userId);
        List<UserWxIntegraDetaillVo> list = service.getUserIntegralDetail(query);
        PageInfo<UserWxIntegraDetaillVo> pageInfo = new PageInfo<>(list);
        return new PageUtils<>(pageInfo);
    }
}
